package com.example.bootintegration.datasource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author Quintoy
 * @date 12/30/22
 */
public class PrimaryDataSourceProcessor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {

    private final String DEFAULT_CONFIG = "test";

    private ApplicationContext context;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(DEFAULT_CONFIG + "JdbcTemplate");
        if (beanDefinition != null) {
            beanDefinition.setPrimary(true);
        }
        BeanDefinition beanDefinitionTransaction = beanFactory.getBeanDefinition(DEFAULT_CONFIG + "TransactionManager");
        if (beanDefinitionTransaction != null) {
            beanDefinitionTransaction.setPrimary(true);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
